package com.yp.infrastructure.mvc.session;


import com.yp.infrastructure.mvc.exception.EnumErrorMessage;
import com.yp.infrastructure.mvc.exception.MvcException;
import org.springframework.stereotype.Component;

@Component
public class UserSession {

    private final ThreadLocal<Object> threadLocal = new InheritableThreadLocal<>();



    /**
     * Relate a actor with a actor session.
     */
    public UserSession bind(final Object user) {
        threadLocal.set(user);
        return this;
    }

    /**
     * Unbind a actor session.
     */
    public Object unbind() {
        threadLocal.remove();
        return this;
    }

    /**
     * Return an effective actor. When You are not related, an anonymous is returned.
     */
    public Object  get(boolean e) {
         Object user = threadLocal.get();
        if (null == user && e) throw new MvcException(EnumErrorMessage.SessionNotFound);
        return user;
    }


    public Object get() {
        return threadLocal.get();
    }
}
